using System;
using System.Drawing;
using System.IO;
using System.Text;

namespace Img2ASCII
{
    public class Img2ASCIIHelper
    {

        //string asciiStrs= "@#S%?*+;:,.";
        //这个效果好像更好

        static void Main(string[] args)
        {
            string imgPath = "D:/Documents/Pictures/1.jpg";
            int outputWidth = 150;

            string str = ProcessImage(imgPath, outputWidth, "  .,:ilwW@@");

            Console.Write(str);

            //回置0行
            Console.SetCursorPosition(0, 0);

            Console.ReadKey();

        }

        /// <summary>
        /// 将图片转为ASCII字符
        /// </summary>
        /// <param name="imgPath"></param>
        /// <param name="outputWidth"></param>
        /// <param name="GrayImg2ASCIIStrs">灰度图映射到对应的字符序列</param>
        /// <returns></returns>
        public static string ProcessImage(string imgPath, int outputWidth, string GrayImg2ASCIIStrs)
        {
            if (string.IsNullOrEmpty(imgPath)
                || outputWidth <= 0
                || !File.Exists(imgPath))
            {
                return string.Empty;
            }


            StringBuilder sb = new StringBuilder();
            using (Bitmap img = new Bitmap(imgPath))
            {
                double aspectRatio = (double)img.Height / img.Width;
                int outputHeight = (int)(outputWidth * aspectRatio);

                using (Bitmap resizedImg = new Bitmap(img, new Size(outputWidth, outputHeight)))
                {

                    for (int y = 0; y < resizedImg.Height; y++)
                    {
                        for (int x = 0; x < resizedImg.Width; x++)
                        {
                            Color pixcelCOlor = resizedImg.GetPixel(x, y);
                            int grayValue = (pixcelCOlor.R + pixcelCOlor.G + pixcelCOlor.B) / 3;

                            //灰度最大总是255，所以不会有idx越界的情况（可直接看成grayValue/256*Str.Length)
                            int index = grayValue * GrayImg2ASCIIStrs.Length / 256;

                            sb.Append(GrayImg2ASCIIStrs[index]);
                        }

                        sb.AppendLine();
                    }
                }
            }
            return sb.ToString();
        }
    }
}
